package bank;

import java.util.Calendar;
import java.util.Hashtable;

public class BankVault
{
    private static long fib = 50;
    
    static Hashtable<String, Account> accounts = new Hashtable<String, Account>();
    
    /*
     * TODO For this to be multiplayer we need to make these into web services or connecting to a
     * database rather then a hashtable. Could use a mysql database, should be simple or CORBA????
     * FOR SINGLE PLAYER WE SHOULD PROBABLY USE SQLITE DATABASE
     */
    public void createAccount(String userName, String password)
    {
        Calendar rightNow = Calendar.getInstance();

        String accountNumber = new Long(rightNow.get(Calendar.YEAR)).toString()
            + new Long(rightNow.get(Calendar.DAY_OF_MONTH)).toString()
            + new Long(rightNow.get(Calendar.MONTH)).toString();
        
        
        String random = new Long(fib(getFib())).toString();
        int i = random.length();
        int remainder = 14 - accountNumber.length();
        // strip off the needed numbers to complete a 14 digit bankcode from the random number
        // generated
        while (i < remainder)
        {
            Character t = random.charAt(i);
            accountNumber += t.toString();
            i++;
        }
        // check that this code does not represent an existing account number
        Account tmp = accounts.get(accountNumber);
        if (tmp == null)
        {
            Account yourAccount = new Account(userName, accountNumber.trim(), password);
            accounts.put(accountNumber.trim(), yourAccount);
        }
        else
        {
            createAccount(userName, password);
        }
        
    }
    
    public static Account getAccount(String accountNo)
    {
        try
        {
            return accounts.get(accountNo);
        }
        catch (Exception e)
        {
            return null;
        }
    }
    
    /*
     * for creating a random unique number for account number for each new customer notice the fib
     * starts at 38 so to have a series of numbers that are at least 8 digits long
     */
    private Long fib(long fib)
    {
        if (fib <= 1)
        {
            fib = 50;
            fib(BankVault.getFib());
        }
        else
        {
            BankVault.setFib(fib);
            return fib(BankVault.getFib() - 1) + fib(BankVault.getFib() - 2);
        }
        return fib;
    }
    
    public static void setFib(long fib)
    {
        BankVault.fib = fib;
    }
    
    public static long getFib()
    {
        return fib;
    }
    
}
